/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.financial.web.taxclearance;

import com.alibaba.fastjson.JSONArray;
import com.jeesite.common.collect.ListUtils;
import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.idgen.IdGen;
import com.jeesite.common.lang.DateUtils;
import com.jeesite.common.lang.NumberUtils;
import com.jeesite.common.lang.ObjectUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.ar.entity.Tar;
import com.jeesite.modules.ar.entity.TarDetail;
import com.jeesite.modules.ar.service.TarService;
import com.jeesite.modules.base.dao.investorfinancialinfo.PadTaxInterestDao;
import com.jeesite.modules.base.entity.cars.Tcar;
import com.jeesite.modules.base.entity.customer.Customer;
import com.jeesite.modules.base.entity.fixedexpense.CustomerPrice;
import com.jeesite.modules.base.entity.fixedexpense.FixedExpense;
import com.jeesite.modules.base.entity.investorfinancialinfo.InvestorFinancialInfo;
import com.jeesite.modules.base.entity.investorfinancialinfo.PadTaxInterest;
import com.jeesite.modules.base.entity.supplier.Supplier;
import com.jeesite.modules.base.service.cars.TcarService;
import com.jeesite.modules.base.service.customer.CustomerService;
import com.jeesite.modules.base.service.fixedexpense.FixedExpenseService;
import com.jeesite.modules.base.service.investorfinancialinfo.InvestorFinancialInfoService;
import com.jeesite.modules.base.service.supplier.SupplierService;
import com.jeesite.modules.financial.dao.taxclearance.TaxClearanceDetailDao;
import com.jeesite.modules.financial.entity.taxclearance.TaxClearance;
import com.jeesite.modules.financial.entity.taxclearance.TaxClearanceDetail;
import com.jeesite.modules.financial.service.taxclearance.TaxClearanceService;
import com.jeesite.modules.logistics.dao.customsdeclaration.CustomsDeclarationDetailDao;
import com.jeesite.modules.logistics.entity.customsdeclaration.CustomsDeclaration;
import com.jeesite.modules.logistics.entity.customsdeclaration.CustomsDeclarationDetail;
import com.jeesite.modules.logistics.service.customsdeclaration.CustomsDeclarationService;
import com.jeesite.modules.order.dao.serviceorder.ServiceOrderDetailDao;
import com.jeesite.modules.order.entity.serviceorder.RelatedRecord;
import com.jeesite.modules.order.entity.serviceorder.ServiceOrder;
import com.jeesite.modules.order.entity.serviceorder.ServiceOrderDetail;
import com.jeesite.modules.order.service.serviceorder.ServiceOrderService;
import com.jeesite.modules.payment.entity.Tap;
import com.jeesite.modules.payment.entity.TapDetail;
import com.jeesite.modules.payment.service.TapService;
import com.jeesite.modules.prepay.entity.Tprepayment;
import com.jeesite.modules.prepay.entity.TprepaymentEstimated;
import com.jeesite.modules.prepay.service.TprepaymentService;
import com.jeesite.modules.prerecieve.entity.TadvancesReceived;
import com.jeesite.modules.prerecieve.entity.TadvancesReceivedEstimated;
import com.jeesite.modules.prerecieve.service.TadvancesReceivedService;
import com.jeesite.modules.sys.entity.EmpUser;
import com.jeesite.modules.sys.service.EmpUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 通关缴税Controller
 *
 * @author Kilo
 * @version 2021-03-10
 */
@Controller
@RequestMapping(value = "${adminPath}/financial/taxclearance/taxClearance")
public class TaxClearanceController extends BaseController {

    @Autowired
    private TaxClearanceService taxClearanceService;
    @Autowired
    private CustomsDeclarationDetailDao customsDeclarationDetailDao;
    @Autowired
    private ServiceOrderService serviceOrderService;
    @Autowired
    private ServiceOrderDetailDao serviceOrderDetailDao;
    @Autowired
    private TcarService tcarService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private SupplierService supplierService;
    @Autowired
    private CustomsDeclarationService customsDeclarationService;
    @Autowired
    private InvestorFinancialInfoService investorFinancialInfoService;
    @Autowired
    private PadTaxInterestDao padTaxInterestDao;
    @Autowired
    private EmpUserService empUserService;
    @Autowired
    private TapService tapService;
    @Autowired
    private TarService tarService;
    @Autowired
    private TprepaymentService tprepaymentService;
    @Autowired
    private TadvancesReceivedService tadvancesReceivedService;
    @Autowired
    private FixedExpenseService fixedExpenseService;
    @Autowired
    private TaxClearanceDetailDao taxClearanceDetailDao;

    /**
     * 获取数据
     */
    @ModelAttribute
    public TaxClearance get(String taxClearanceId, boolean isNewRecord) {
        return taxClearanceService.get(taxClearanceId, isNewRecord);
    }

    /**
     * 查询列表
     */
    @RequiresPermissions("financial:taxclearance:taxClearance:view")
    @RequestMapping(value = {"list", ""})
    public String list(TaxClearance taxClearance, Model model) {
        model.addAttribute("taxClearance", taxClearance);
        // 车架号
        List < CustomsDeclarationDetail > list = customsDeclarationDetailDao.findList(new CustomsDeclarationDetail());
        model.addAttribute("frameNumberList", list);
        model.addAttribute("listServiceOrder", serviceOrderService.findList(new ServiceOrder()));// 服务订单号
        model.addAttribute("listCustomer", customerService.findList(new Customer()));// 客户
        Supplier gnzf = new Supplier();
        gnzf.setSupplierType("1");
        List < Supplier > gnzfList = supplierService.findList(gnzf);
        model.addAttribute("gnzfList", gnzfList);// 资方
        model.addAttribute("customsBrokerList", supplierService.findList(new Supplier()));// 报关行
        // 车辆
        List < Tcar > tcarList = tcarService.findList(new Tcar());
        model.addAttribute("tcarList", tcarList);
        model.addAttribute("listUser", empUserService.findList(new EmpUser()));
        return "modules/financial/taxclearance/taxClearanceList";
    }

    /**
     * 查询列表数据
     */
    @RequiresPermissions("financial:taxclearance:taxClearance:view")
    @RequestMapping(value = "listData")
    @ResponseBody
    public Page < TaxClearance > listData(TaxClearance taxClearance, HttpServletRequest request, HttpServletResponse response) {
        taxClearance.setPage(new Page <>(request, response));
        Page < TaxClearance > page = taxClearanceService.findPage(taxClearance);
        return page;
    }

    /**
     * 查看编辑表单
     */
    @RequiresPermissions("financial:taxclearance:taxClearance:view")
    @RequestMapping(value = "form")
    public String form(TaxClearance taxClearance, Model model) {
        taxClearance.setStatus1("1");
        model.addAttribute("taxClearance", taxClearance);
        // 车架号
        List < CustomsDeclarationDetail > list = customsDeclarationDetailDao.findList(new CustomsDeclarationDetail());
        model.addAttribute("frameNumberList", list);
//		model.addAttribute("listServiceOrder", serviceOrderService.findList(new ServiceOrder()));// 服务订单号
//		model.addAttribute("listCustomer", customerService.findList(new Customer()));// 客户
        Supplier gnzf = new Supplier();
        gnzf.setSupplierType("1");
        List < Supplier > gnzfList = supplierService.findList(gnzf);
        model.addAttribute("gnzfList", gnzfList);// 资方
//		model.addAttribute("customsBrokerList", supplierService.findList(new Supplier()));// 报关行
        // 车辆
//		List<Tcar> tcarList = tcarService.findList(new Tcar());
//		model.addAttribute("tcarList", tcarList);
        model.addAttribute("listPrepayment", tprepaymentService.findList(new Tprepayment()));
        model.addAttribute("listAp", tapService.findList(new Tap()));
        model.addAttribute("listAdvancesReceived", tadvancesReceivedService.findList(new TadvancesReceived()));
        model.addAttribute("listAr", tarService.findList(new Tar()));
        return "modules/financial/taxclearance/taxClearanceForm";
    }

    /**
     * 通关缴税批量生成
     */
    @RequiresPermissions("financial:taxclearance:taxClearance:edit")
    @RequestMapping(value = "listPl")
    public String listPl(TaxClearance taxClearance, Model model) {
        // 客户
        List < Customer > customerList = customerService.findList(new Customer());
        model.addAttribute("customerList", customerList);
        //服务订单
        List < ServiceOrder > serviceOrderList = serviceOrderService.findList(new ServiceOrder());
        model.addAttribute("serviceOrderList", serviceOrderList);
        //国内资方
        Supplier gnzf = new Supplier();
        gnzf.setSupplierType("1");
        List < Supplier > gnzfList = supplierService.findList(gnzf);
        model.addAttribute("gnzfList", gnzfList);
        //报关行
        model.addAttribute("customsBrokerList", supplierService.findList(new Supplier()));
        //资方垫税方案
        List < InvestorFinancialInfo > ifos = investorFinancialInfoService.findList(new InvestorFinancialInfo());
        //生成文件保存的bizKey
        TaxClearance taxClearance1 = new TaxClearance();
        String id = IdGen.nextId();
        taxClearance1.setId(id);
        model.addAttribute("taxClearance1", taxClearance1);
        model.addAttribute("investorFinancialInfoList", ifos);
        return "modules/financial/taxclearance/taxClearanceListPl";
    }

    /**
     * 根据客户获取报关的服务订单
     *
     * @param serviceOrder
     */
    @RequestMapping(value = "getServiceOrderList")
    @ResponseBody
    public List < CustomsDeclaration > getServiceOrderList(ServiceOrder serviceOrder) {
        CustomsDeclaration customsDeclaration = new CustomsDeclaration();
        customsDeclaration.setCustomerId(serviceOrder.getCustomerId());
        List < CustomsDeclaration > list = customsDeclarationService.findList(customsDeclaration);
        return list;
    }

    /**
     * 根据服务订单获取国内资方
     *
     * @param serviceOrder
     */
    @RequestMapping(value = "getGnzfList")
    @ResponseBody
    public List < CustomsDeclaration > getGnzfList(ServiceOrder serviceOrder) {
        CustomsDeclaration customsDeclaration = new CustomsDeclaration();
        customsDeclaration.setServiceOrderId(serviceOrder.getServiceOrderId());
        List < CustomsDeclaration > list = customsDeclarationService.findList(customsDeclaration);
        return list;
    }

    /**
     * 根据服务订单获取报关行
     */
    @RequestMapping(value = "getCustomBrokerList")
    @ResponseBody
    public List < Map < String, String > > getCustomBrokerList(ServiceOrder serviceOrder) {
        CustomsDeclaration customsDeclaration = new CustomsDeclaration();
        customsDeclaration.setServiceOrderId(serviceOrder.getServiceOrderId());
        List < CustomsDeclaration > list = customsDeclarationService.findList(customsDeclaration);
        List < Map < String, String > > mapList = ListUtils.newArrayList();
        for (CustomsDeclaration customsDeclaration1 : list) {
            Map < String, String > map = new HashMap <>();
            map.put("customsBroker", customsDeclaration1.getCustomsBroker());
            map.put("supplierName", customsDeclaration1.getBrolerSupplier().getSupplierName());
            mapList.add(map);
        }
        return mapList;
    }

    /**
     * 获取车辆信息列表
     */
    @RequestMapping(value = "getCarInfoList")
    @ResponseBody
    public List < CustomsDeclaration > getCarInfoList(CustomsDeclaration customsDeclaration) {
        List < CustomsDeclaration > customsDeclarations = customsDeclarationService.findCarInfoList(customsDeclaration);
        return customsDeclarations;
    }

    /**
     * 获取利息
     */
    @RequestMapping(value = "getInterestList")
    @ResponseBody
    public InvestorFinancialInfo getInterestList(String groupId,Date taxPaymentDate){
        List<PadTaxInterest> padTaxInterestList = padTaxInterestDao.findTaxInterestOrder(groupId);
        double dateDistance = DateUtils.getDistanceOfTwoDate(taxPaymentDate,new Date());
        for (PadTaxInterest padTaxInterest:padTaxInterestList){
            if(dateDistance>padTaxInterest.getStartDays()){
                padTaxInterest.setContainFlag("1");
            }else{
                padTaxInterest.setContainFlag("0");
            }
        }
        InvestorFinancialInfo investorFinancialInfo = new InvestorFinancialInfo();
        investorFinancialInfo.setPadTaxInterestList(padTaxInterestList);
        return investorFinancialInfo;
    }

    /**
     * 查看表单详情
     */
    @RequiresPermissions("financial:taxclearance:taxClearance:view")
    @RequestMapping(value = "detail")
    public String detail(TaxClearance taxClearance, Model model) throws ParseException {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date now = df.parse(df.format(new Date()));
        model.addAttribute("listPrepayment", tprepaymentService.findList(new Tprepayment()));
        model.addAttribute("listAp", tapService.findList(new Tap()));
        model.addAttribute("listAdvancesReceived", tadvancesReceivedService.findList(new TadvancesReceived()));
        model.addAttribute("listAr", tarService.findList(new Tar()));
        // 车架号
        List < CustomsDeclarationDetail > list = customsDeclarationDetailDao.findList(new CustomsDeclarationDetail());
        model.addAttribute("frameNumberList", list);
        // 行号
        List<ServiceOrderDetail> serviceOrderDetailList = null;
        if(StringUtils.isNotEmpty(taxClearance.getServiceOrderId())) {
            serviceOrderDetailList = serviceOrderDetailDao.findByServiceOrderId(taxClearance.getServiceOrderId());
        }else {
            serviceOrderDetailList = serviceOrderDetailDao.findAll();
        }
        model.addAttribute("rowNumber", serviceOrderDetailList.get(0).getRowNumber());
        model.addAttribute("listServiceOrder", serviceOrderService.findList(new ServiceOrder()));// 服务订单号
        model.addAttribute("listCustomer", customerService.findList(new Customer()));// 客户
        Supplier gnzf = new Supplier();
        gnzf.setSupplierType("1");
        List < Supplier > gnzfList = supplierService.findList(gnzf);
        model.addAttribute("gnzfList", gnzfList);// 资方
        model.addAttribute("customsBrokerList", supplierService.findList(new Supplier()));// 报关行
        // 车辆
        List < Tcar > tcarList = tcarService.findList(new Tcar());
        model.addAttribute("tcarList", tcarList);

        if (!"1".equals(taxClearance.getTaxPaymentMethod())) {
            double prepaidAmount = taxClearance.getPrepaidAmount();// 代垫金额
            InvestorFinancialInfo investorFinancialInfo = new InvestorFinancialInfo();
            investorFinancialInfo.setSupplier(taxClearance.getInvestor());
            investorFinancialInfo.setFinancingType("1");
            InvestorFinancialInfo info = investorFinancialInfoService.findList(investorFinancialInfo).get(0);
            Long investorYearDays = info.getDays();// 资方年天数
            List < TaxClearanceDetail > taxClearanceDetailList = taxClearance.getTaxClearanceDetailList();
            List < TaxClearanceDetail > taxClearanceDetailList1 = ListUtils.newArrayList();
            List < TaxClearanceDetail > taxClearanceDetailList2 = ListUtils.newArrayList();
            Double investorInterestTotal = 0D;//资方利息合计
            Double customerInterestTotal = 0D;//客户利息合计
            for (TaxClearanceDetail taxClearanceDetail : taxClearanceDetailList) {
                if ("1".equals(taxClearanceDetail.getType())) {
                    Double interest = null;
                    if(!"2".equals(taxClearance.getTaxPaymentMethod())) {
                        // 计算资方利息
                        double investorDetailRatio = NumberUtils.div(Double.parseDouble(taxClearanceDetail.getInterestRate()), 100); //资方利率
                        double investorDetailDays = 0D;
                        if (now.compareTo(taxClearanceDetail.getStartDate()) >= 0 && now.compareTo(taxClearanceDetail.getEndDate()) <= 0) {
                            investorDetailDays = DateUtils.getDistanceOfTwoDate(taxClearanceDetail.getStartDate(), now);
                        } else if (now.compareTo(taxClearanceDetail.getStartDate()) >= 0 && now.compareTo(taxClearanceDetail.getEndDate()) > 0) {
                            investorDetailDays = DateUtils.getDistanceOfTwoDate(taxClearanceDetail.getStartDate(), taxClearanceDetail.getEndDate());
                        }
                        interest = NumberUtils.mul(NumberUtils.div(NumberUtils.mul(prepaidAmount, investorDetailRatio), investorYearDays), investorDetailDays);
                    }else{
                        //关税方式允许利率为空
                        interest = this.calcGSInterest("1",taxClearance.getPadTaxMode(),taxClearance.getTaxPaymentDate());
                    }
                    taxClearanceDetail.setInterest(interest);
                    investorInterestTotal = NumberUtils.add(investorInterestTotal, interest);
                    taxClearanceDetailList1.add(taxClearanceDetail);
                } else if ("2".equals(taxClearanceDetail.getType())) {
                    Double interest = null;
                    if(!"2".equals(taxClearance.getTaxPaymentMethod())) {
                        double customerDetailRatio = NumberUtils.div(Double.parseDouble(taxClearanceDetail.getInterestRate()), 100); //客户利率
                        double customerDetailDays = 0D;
                        if (now.compareTo(taxClearanceDetail.getStartDate()) >= 0 && now.compareTo(taxClearanceDetail.getEndDate()) <= 0) {
                            customerDetailDays = DateUtils.getDistanceOfTwoDate(taxClearanceDetail.getStartDate(), now);
                        } else if (now.compareTo(taxClearanceDetail.getStartDate()) >= 0 && now.compareTo(taxClearanceDetail.getEndDate()) > 0) {
                            customerDetailDays = DateUtils.getDistanceOfTwoDate(taxClearanceDetail.getStartDate(), taxClearanceDetail.getEndDate());
                        }
                        interest = NumberUtils.mul(NumberUtils.div(NumberUtils.mul(prepaidAmount, customerDetailRatio), 360), customerDetailDays);
                    }else{
                        //关税方式允许利率为空
                        interest =
                                this.calcGSInterest("2",taxClearance.getPadTaxMode(),taxClearance.getTaxPaymentDate());
                    }
                    taxClearanceDetail.setInterest(interest);
                    customerInterestTotal = NumberUtils.add(customerInterestTotal, interest);
                    taxClearanceDetailList2.add(taxClearanceDetail);
                }
            }
            taxClearance.setInvestorRealTimeInterest(investorInterestTotal);
            taxClearance.setCustomerRealTimeInterest(customerInterestTotal);
            taxClearance.setTaxClearanceDetailList1(taxClearanceDetailList1);
            taxClearance.setTaxClearanceDetailList2(taxClearanceDetailList2);
        }
        // 相关记录
        List < RelatedRecord > relatedRecordList = ListUtils.newArrayList();
        // 应收单
        Tar tar = new Tar();
        tar.setParentBillCode(taxClearance.getTaxClearanceId());
        List < Tar > list2 = tarService.findList(tar);
        for (Tar tar1 : list2) {
            for (TarDetail tarDetail : tarService.get(tar1).getTarDetailList()) {
                RelatedRecord relatedRecord = new RelatedRecord();
                relatedRecord.setBillCode(tar1.getArCode());
                relatedRecord.setDate(tar1.getDate());
                relatedRecord.setExpenseItem(fixedExpenseService.get(tarDetail.getExpenseItem()).getFixedExpenseName());
                relatedRecord.setYingshouAmount(tarDetail.getApAmount());
                relatedRecordList.add(relatedRecord);
            }
        }
        // 应付单
        Tap tap = new Tap();
        tap.setParentBillCode(taxClearance.getTaxClearanceId());
        List < Tap > list1 = tapService.findList(tap);
        for (Tap tap1 : list1) {
            for (TapDetail tapDetail : tapService.get(tap1).getTapDetailList()) {
                RelatedRecord relatedRecord = new RelatedRecord();
                relatedRecord.setBillCode(tap1.getApCode());
                relatedRecord.setDate(tap1.getDate());
                relatedRecord.setExpenseItem(fixedExpenseService.get(tapDetail.getExpenseItem()).getFixedExpenseName());
                relatedRecord.setYingfuAmount(tapDetail.getApAmount());
                relatedRecordList.add(relatedRecord);
            }
        }

        // 预收单
        TadvancesReceived tadvancesReceived = new TadvancesReceived();
        tadvancesReceived.setParentBillCode(taxClearance.getTaxClearanceId());
        List < TadvancesReceived > list4 = tadvancesReceivedService.findList(tadvancesReceived);
        for (TadvancesReceived tadvancesReceived1 : list4) {
            for (TadvancesReceivedEstimated tadvancesReceivedEstimated : tadvancesReceivedService.get(tadvancesReceived1).getTadvancesReceivedEstimatedList()) {
                RelatedRecord relatedRecord = new RelatedRecord();
                relatedRecord.setBillCode(tadvancesReceived1.getAdvancesReceivedCode());
                relatedRecord.setDate(tadvancesReceived1.getDate());
                relatedRecord.setExpenseItem(fixedExpenseService.get(tadvancesReceivedEstimated.getAdvancesReceivedType()).getFixedExpenseName());
                relatedRecord.setYushouAmount(tadvancesReceivedEstimated.getEstimatedReceivedAmount());
                relatedRecordList.add(relatedRecord);
            }
        }

        // 预付单
        Tprepayment tprepayment = new Tprepayment();
        tprepayment.setParentBillCode(taxClearance.getTaxClearanceId());
        List < Tprepayment > list5 = tprepaymentService.findList(tprepayment);
        for (Tprepayment tprepayment1 : list5) {
            for (TprepaymentEstimated tprepaymentEstimated : tprepaymentService.get(tprepayment1).getTprepaymentEstimatedList()) {
                RelatedRecord relatedRecord = new RelatedRecord();
                relatedRecord.setBillCode(tprepayment1.getPrepaymentCode());
                relatedRecord.setDate(tprepayment1.getDate());
                relatedRecord.setExpenseItem(fixedExpenseService.get(tprepaymentEstimated.getPrepaymentType()).getFixedExpenseName());
                relatedRecord.setYushouAmount(tprepaymentEstimated.getEstimatedPaymentAmount());
                relatedRecordList.add(relatedRecord);
            }
        }
        taxClearance.setRelatedRecordList(relatedRecordList);
        model.addAttribute("taxClearance", taxClearance);
        return "modules/financial/taxclearance/taxClearanceDetail";
    }

    /**
     * 计算关税利息
     */
    public double calcGSInterest(String type,String groupId,Date date){
        double distanceDays = DateUtils.getDistanceOfTwoDate(date,new Date());
        double interest =0d;
        if(type.equals("1")){
            List<PadTaxInterest> padTaxInterestList1 = padTaxInterestDao.findInvestorTaxInterestOrder(groupId);
            for(PadTaxInterest padTaxInterest:padTaxInterestList1){
                if(distanceDays>padTaxInterest.getStartDays()){
                    interest = interest + padTaxInterest.getInvestorInterestAmount();
                }
            }
        }else{
            List<PadTaxInterest> padTaxInterestList2 = padTaxInterestDao.findCustomerTaxInterestOrder(groupId);
            for(PadTaxInterest padTaxInterest:padTaxInterestList2){
                if(distanceDays>padTaxInterest.getStartDays()){
                    interest = interest + padTaxInterest.getCustomerInterestAmount();
                }
            }
        }
        return interest;
    }

    /**
     * 批量生成通关缴税信息
     */
    @PostMapping(value = "savePL")
    @ResponseBody
    public String savePL(String customerId, String serviceOrderId, String investorId, String customsBroker, String taxPaymentMethod, Date taxPaymentDate, String padTaxMode, String prepaidAmount, String amount, String padTaxMemo, String status1, String bizKey, String taxClearanceDetailList1, String taxClearanceDetailList2, String carInfoList) {
        TaxClearance taxClearance = new TaxClearance();
        taxClearance.setCustomerId(customerId);
        taxClearance.setServiceOrderId(serviceOrderId);
        taxClearance.setInvestorId(investorId);
        taxClearance.setCustomsBroker(customsBroker);
        taxClearance.setTaxPaymentMethod(taxPaymentMethod);
        taxClearance.setTaxPaymentDate(taxPaymentDate);
        taxClearance.setPadTaxMode(padTaxMode);
        if (StringUtils.isNotEmpty(prepaidAmount)) {
            taxClearance.setPrepaidAmount(Double.parseDouble(prepaidAmount));
        }
        if (StringUtils.isNotEmpty(amount)) {
            taxClearance.setAmount(Double.parseDouble(amount));
        }
        taxClearance.setPadTaxMemo(padTaxMemo);
        taxClearance.setStatus1(status1);
        taxClearance.setId(bizKey);
        //获取关联信息
        if ("1".equals(taxClearance.getTaxPaymentMethod())) { // 代收代付
            if (taxClearance.getAmount() == null) {
                return renderResult(Global.FALSE, text("请填写代收代付金额！"));
            }
        } else {
            if (StringUtils.isEmpty(taxClearance.getPadTaxMode())) {
                return renderResult(Global.FALSE, text("请填写垫税模式！"));
            }
            if (taxClearance.getPrepaidAmount() == null) {
                return renderResult(Global.FALSE, text("请填写代垫金额！"));
            }
        }
        taxClearance.setCustomer(customerService.get(taxClearance.getCustomerId()));
        //获取报关信息
        CustomsDeclaration customsDeclaration = new CustomsDeclaration();
        customsDeclaration.setServiceOrderId(serviceOrderId);
        customsDeclaration.setCustomerId(customerId);
        customsDeclaration.setInvestorId(investorId);
        customsDeclaration.setCustomsBroker(customsBroker);
        List < CustomsDeclaration > customsDeclarationFinals = customsDeclarationService.findList(customsDeclaration);
        CustomsDeclaration customsDeclarationFinal = customsDeclarationFinals.get(0);
        taxClearance.setCurrency(customsDeclarationFinal.getCurrency());
        taxClearance.setTaxDate(customsDeclarationFinal.getTaxDate());
        taxClearance.setTaxPaymentDeadline(customsDeclarationFinal.getTaxDeadlineDate());
        List < TaxClearanceDetail > staxClearanceDetailList1 = JSONArray.parseArray(taxClearanceDetailList1, TaxClearanceDetail.class);
        List < TaxClearanceDetail > staxClearanceDetailList2 = JSONArray.parseArray(taxClearanceDetailList2, TaxClearanceDetail.class);
        List < TaxClearanceDetail > list = ListUtils.newArrayList();
        if (ListUtils.isNotEmpty(staxClearanceDetailList1)) {
            list.addAll(staxClearanceDetailList1);
        }
        if (ListUtils.isNotEmpty(staxClearanceDetailList2)) {
            list.addAll(staxClearanceDetailList2);
        }
        taxClearance.setTaxClearanceDetailList(list);
        List < ServiceOrderDetail > scarInfoList = JSONArray.parseArray(carInfoList, ServiceOrderDetail.class);
        for (ServiceOrderDetail serviceOrderDetail : scarInfoList) {
            if (serviceOrderDetail.getModel().equals("已生成")) {
                return renderResult(Global.FALSE, text("已生成不可再生成！"));
            }
        }
        for (ServiceOrderDetail serviceOrderDetail : scarInfoList) {
            if (serviceOrderDetail.getCustomsDeclarationDetailId().equals("true")) {
                TaxClearance taxClearance1 = (TaxClearance) ObjectUtils.cloneBean(taxClearance);
                taxClearance1.setFrameNumber(serviceOrderDetail.getFrameNumber());
                taxClearance1.setCarId(serviceOrderDetail.getCarId());
                taxClearance1.setArea(serviceOrderDetail.getArea());
                //获取报关明细信息
                CustomsDeclarationDetail customsDeclarationDetail = new CustomsDeclarationDetail();
                customsDeclarationDetail.setCustomsDeclarationId(customsDeclarationFinal);
                customsDeclarationDetail.setFrameNumber(serviceOrderDetail.getFrameNumber());
                customsDeclarationDetail.setCarId(serviceOrderDetail.getCarId());
                List < CustomsDeclarationDetail > customsDeclarationDetailFinals = customsDeclarationDetailDao.findPList(customsDeclarationDetail);
                if (ListUtils.isNotEmpty(customsDeclarationDetailFinals)) {
                    CustomsDeclarationDetail customsDeclarationDetailFinal = customsDeclarationDetailFinals.get(0);
                    taxClearance1.setDeclaredPrice(customsDeclarationDetailFinal.getDeclaredPrice());
                    taxClearance1.setTaxPrice(customsDeclarationDetailFinal.getTaxPrice());
                    taxClearance1.setDifference(NumberUtils.sub(customsDeclarationDetailFinal.getDeclaredPrice(), customsDeclarationDetailFinal.getTaxPrice()));
                    taxClearance1.setCustomsCombinedTaxRate(customsDeclarationDetailFinal.getCustomsCombinedTaxRate());
                    taxClearance1.setComprehensiveTax(customsDeclarationDetailFinal.getComprehensiveTax());
                    taxClearance1.setForeignCurrencyPrice(customsDeclarationDetailFinal.getForeignCurrencyPrice());
                    taxClearance1.setCustomsExchangeRate(customsDeclarationDetailFinal.getCustomsExchangeRate());
                    taxClearance1.setIsNewRecord(true);
                    //获取对应service_order_detail下的所有row_number
                    List<ServiceOrderDetail>  serviceOrderDetailList = serviceOrderDetailDao.findByServiceOrderId(serviceOrderId);
                    for (ServiceOrderDetail serviceOrderDetail1:serviceOrderDetailList) {
                        taxClearance1.setRowNumber(serviceOrderDetail1.getRowNumber());
                        taxClearanceService.save(taxClearance1);
                    }
                }
            }
        }
        return renderResult(Global.TRUE, text("批量生成通关缴税成功！"));
    }

    /**
     * 保存数据
     */
    @RequiresPermissions("financial:taxclearance:taxClearance:edit")
    @PostMapping(value = "save")
    @ResponseBody
    public String save(@Validated TaxClearance taxClearance) {
        // 代收代付
        if ("1".equals(taxClearance.getTaxPaymentMethod())) {
            if (taxClearance.getAmount() == null) {
                return renderResult(Global.FALSE, text("请填写代收代付金额！"));
            }
        } else {
            if (StringUtils.isEmpty(taxClearance.getPadTaxMode())) {
                return renderResult(Global.FALSE, text("请填写垫税模式！"));
            }
            if (taxClearance.getPrepaidAmount() == null) {
                return renderResult(Global.FALSE, text("请填写代垫金额！"));
            }
        }
        // 是否资方垫付
        if ("1".equals(taxClearance.getIsinvpad())) {
            if (StringUtils.isEmpty(taxClearance.getInvestorId())) {
                return renderResult(Global.FALSE, text("国内资方不能为空！"));
            }
        } else {
            if (StringUtils.isEmpty(taxClearance.getCompany().getCompanyCode())) {
                return renderResult(Global.FALSE, text("垫付方不能为空！"));
            }
        }
        taxClearance.setCustomer(customerService.get(taxClearance.getCustomerId()));
        // 行号
        List<ServiceOrderDetail> serviceOrderDetailList = null;
        if(StringUtils.isNotEmpty(taxClearance.getServiceOrderId())) {
            serviceOrderDetailList = serviceOrderDetailDao.findByServiceOrderId(taxClearance.getServiceOrderId());
        }
        taxClearance.setRowNumber(serviceOrderDetailList.get(0).getRowNumber());
        List < TaxClearanceDetail > taxClearanceDetailList1 = taxClearance.getTaxClearanceDetailList1();
        List < TaxClearanceDetail > taxClearanceDetailList2 = taxClearance.getTaxClearanceDetailList2();
        List < TaxClearanceDetail > list = ListUtils.newArrayList();
        list.addAll(taxClearanceDetailList1);
        list.addAll(taxClearanceDetailList2);
        taxClearance.setTaxClearanceDetailList(list);
        taxClearanceService.save(taxClearance);
        return renderResult(Global.TRUE, text("保存通关缴税成功！"));
    }

    /**
     * 删除数据
     */
    @RequiresPermissions("financial:taxclearance:taxClearance:edit")
    @RequestMapping(value = "delete")
    @ResponseBody
    public String delete(TaxClearance taxClearance) {
        taxClearanceService.delete(taxClearance);
        return renderResult(Global.TRUE, text("删除通关缴税成功！"));
    }

    /**
     * 获取行号
     */
    @RequestMapping(value = "getRowNumbers")
    @ResponseBody
    public List<ServiceOrderDetail> getRowNumbers(@RequestParam("frameNumber") String frameNumber) {
        ServiceOrderDetail serviceOrderDetail = new ServiceOrderDetail();
        serviceOrderDetail.setFrameNumber(frameNumber);
        List<ServiceOrderDetail> serviceOrderDetailList= serviceOrderDetailDao.findList(serviceOrderDetail);
        return serviceOrderDetailList;
    }

    /**
     * 获取车辆信息
     *
     * @param frameNumber
     */
    @RequestMapping(value = "getCarInfo")
    @ResponseBody
    public CustomsDeclarationDetail getCarInfo(@RequestParam("frameNumber") String frameNumber) {
        CustomsDeclarationDetail customsDeclarationDetail = new CustomsDeclarationDetail();
        customsDeclarationDetail.setFrameNumber(frameNumber);
        CustomsDeclarationDetail detail = customsDeclarationDetailDao.findList(customsDeclarationDetail).get(0);
        return detail;
    }

    /**
     * 获取车辆信息
     *
     * @param frameNumber
     */
    @RequestMapping(value = "getCarInfo2")
    @ResponseBody
    public CustomsDeclarationDetail getCarInfo2(@RequestParam("frameNumber") String frameNumber,@RequestParam("rowNumber") Long rowNumber) {
        CustomsDeclarationDetail customsDeclarationDetail = new CustomsDeclarationDetail();
        customsDeclarationDetail.setFrameNumber(frameNumber);
        customsDeclarationDetail.setRowNumber(rowNumber);
        CustomsDeclarationDetail detail = customsDeclarationDetailDao.findList(customsDeclarationDetail).get(0);
        return detail;
    }

    /**
     * 获取服务订单信息
     *
     * @param frameNumber
     */
    @RequestMapping(value = "getServiceOrderInfo")
    @ResponseBody
    public ServiceOrder getServiceOrderInfo(@RequestParam("frameNumber") String frameNumber) {
        ServiceOrderDetail serviceOrderDetail = new ServiceOrderDetail();
        serviceOrderDetail.setFrameNumber(frameNumber);
        List < ServiceOrderDetail > list = serviceOrderDetailDao.findList(serviceOrderDetail);
        for (ServiceOrderDetail orderDetail : list) {
            ServiceOrder serviceOrder = serviceOrderService.get(orderDetail.getServiceOrderId());
            if (serviceOrder.getOrderStatus() != "6") {
                return serviceOrder;
            }
        }
        return null;
    }

    /**
     * 获取服务订单信息
     *
     * @param frameNumber
     */
    @RequestMapping(value = "getServiceOrderInfo2")
    @ResponseBody
    public ServiceOrder getServiceOrderInfo2(@RequestParam("frameNumber") String frameNumber,@RequestParam("rowNumber") Long rowNumber) {
        ServiceOrderDetail serviceOrderDetail = new ServiceOrderDetail();
        serviceOrderDetail.setFrameNumber(frameNumber);
        serviceOrderDetail.setRowNumber(rowNumber);
        List < ServiceOrderDetail > list = serviceOrderDetailDao.findList(serviceOrderDetail);
        for (ServiceOrderDetail orderDetail : list) {
            ServiceOrder serviceOrder = serviceOrderService.get(orderDetail.getServiceOrderId());
            if (serviceOrder.getOrderStatus() != "6") {
                return serviceOrder;
            }
        }
        return null;
    }

    /**
     * 获取报关信息
     *
     * @param frameNumber
     */
    @RequestMapping(value = "getCustomsDeclarationInfo")
    @ResponseBody
    public CustomsDeclaration getCustomsDeclarationInfo(@RequestParam("frameNumber") String frameNumber) {
        CustomsDeclarationDetail customsDeclarationDetail = new CustomsDeclarationDetail();
        customsDeclarationDetail.setFrameNumber(frameNumber);
        CustomsDeclarationDetail detail = customsDeclarationDetailDao.findList(customsDeclarationDetail).get(0);
        CustomsDeclaration customsDeclaration = customsDeclarationService.get(detail.getCustomsDeclarationId());
        return customsDeclaration;
    }

    /**
     * 获取报关信息2
     *
     * @param frameNumber
     */
    @RequestMapping(value = "getCustomsDeclarationInfo2")
    @ResponseBody
    public CustomsDeclaration getCustomsDeclarationInfo2(@RequestParam("frameNumber") String frameNumber,@RequestParam("rowNumber") Long rowNumber) {
        CustomsDeclarationDetail customsDeclarationDetail = new CustomsDeclarationDetail();
        customsDeclarationDetail.setFrameNumber(frameNumber);
        customsDeclarationDetail.setRowNumber(rowNumber);
        CustomsDeclarationDetail detail = customsDeclarationDetailDao.findList(customsDeclarationDetail).get(0);
        CustomsDeclaration customsDeclaration = customsDeclarationService.get(detail.getCustomsDeclarationId());
        return customsDeclaration;
    }

    /**
     * 获取垫税模式列表
     *
     * @param supplierId
     * @param taxPaymentMethod
     */
    @RequestMapping(value = "getList")
    @ResponseBody
    public List < InvestorFinancialInfo > getList(@RequestParam("supplierId") String supplierId, @RequestParam("taxPaymentMethod") String taxPaymentMethod) {
        String method = "";
        if("2".equals(taxPaymentMethod)){
            method = "1";
        } else if("3".equals(taxPaymentMethod)){
            method = "2";
        } else if("4".equals(taxPaymentMethod)){
            method = "3";
        } else if("5".equals(taxPaymentMethod)){
            method = "4";
        }
        InvestorFinancialInfo info = new InvestorFinancialInfo();
        Supplier supplier = new Supplier();
        supplier.setSupplierId(supplierId);
        info.setSupplier(supplier);
        info.setFinancingType("3");
        info.setPadtaxType(method);
        List < InvestorFinancialInfo > list = investorFinancialInfoService.findList(info);
        return list;
    }

    /**
     * 获取垫税模式明细
     *
     * @param id
     */
    @RequestMapping(value = "getDetailList")
    @ResponseBody
    public InvestorFinancialInfo getDetailList(@RequestParam("id") String id) {
        InvestorFinancialInfo info = investorFinancialInfoService.get(id);
        List < PadTaxInterest > collect = padTaxInterestDao.findList(new PadTaxInterest(info));
        info.setPadTaxInterestList1(collect);
        return info;
    }

    /**
     * 客户还税按钮
     */
    @RequiresPermissions("financial:taxclearance:taxClearance:edit")
    @RequestMapping(value = "customerTax")
    public String customerTax(TaxClearance taxClearance, Model model) {
        model.addAttribute("taxClearance", taxClearance);
        return "modules/financial/taxclearance/customerTaxForm";
    }

    /**
     * 资方还税按钮
     */
    @RequiresPermissions("financial:taxclearance:taxClearance:edit")
    @RequestMapping(value = "investorTax")
    public String investorTax(TaxClearance taxClearance, Model model) {
        model.addAttribute("taxClearance", taxClearance);
        return "modules/financial/taxclearance/investorTaxForm";
    }

    /**
     * 保存客户还税信息
     */
    @RequiresPermissions("financial:taxclearance:taxClearance:edit")
    @PostMapping(value = "customerTaxSave")
    @ResponseBody
    @Transactional(readOnly = false)
    public String customerTaxSave(TaxClearance t) {
        Date customerActualRepaymentDate = t.getCustomerActualRepaymentDate();
        TaxClearance taxClearance = taxClearanceService.get(t);
        double prepaidAmount = taxClearance.getPrepaidAmount();// 代垫金额
        List < TaxClearanceDetail > taxClearanceDetailList = taxClearance.getTaxClearanceDetailList();
        Double customerPadTaxInterest = 0D; // 客户垫税利息
        Double customerPadTaxYqInterest = 0D; // 客户垫税延期利息
        for (int i = 0; i < taxClearanceDetailList.size(); i++) {
            TaxClearanceDetail taxClearanceDetail = taxClearanceDetailList.get(i);
            if ("2".equals(taxClearanceDetail.getType())) {
                double customerDetailRatio = NumberUtils.div(Double.parseDouble(taxClearanceDetail.getInterestRate()), 100); //客户利率
                double customerDetailDays = 0D;
                if (customerActualRepaymentDate.compareTo(taxClearanceDetail.getStartDate()) >= 0 && customerActualRepaymentDate.compareTo(taxClearanceDetail.getEndDate()) <= 0) {
                    customerDetailDays = DateUtils.getDistanceOfTwoDate(taxClearanceDetail.getStartDate(), customerActualRepaymentDate);
                } else if (customerActualRepaymentDate.compareTo(taxClearanceDetail.getStartDate()) >= 0 && customerActualRepaymentDate.compareTo(taxClearanceDetail.getEndDate()) > 0) {
                    customerDetailDays = DateUtils.getDistanceOfTwoDate(taxClearanceDetail.getStartDate(), taxClearanceDetail.getEndDate());
                }
                if (i == 0) {
                    customerPadTaxInterest = NumberUtils.mul(NumberUtils.div(NumberUtils.mul(prepaidAmount, customerDetailRatio), 360), customerDetailDays);
                } else {
                    double interest = NumberUtils.mul(NumberUtils.div(NumberUtils.mul(prepaidAmount, customerDetailRatio), 360), customerDetailDays);
                    customerPadTaxYqInterest = NumberUtils.add(customerPadTaxYqInterest, interest);
                }

            }
        }
        taxClearance.setCustomerActualDays((long) DateUtils.getDistanceOfTwoDate(taxClearance.getTaxPaymentDate(), customerActualRepaymentDate));
        taxClearance.setCustomerPadTaxInterest(customerPadTaxInterest);
        taxClearance.setCustomerPadTaxYqInterest(customerPadTaxYqInterest);
        taxClearanceService.save(taxClearance);
        // 生成客户应收
        Tar ar = new Tar();
        ar.setCustomer(taxClearance.getCustomer());
        ar.setCustomerId(taxClearance.getCustomer().getCustomerId());
        ar.setDate(new Date());
        ar.setStatus1("1");
        ar.setBillStatus("2");// 已提交
        ar.setServiceOrderId(taxClearance.getServiceOrderId());
        double benjin = taxClearance.getPrepaidAmount();
        double lixi = taxClearance.getCustomerPadTaxInterest();
        double yanqilixi = taxClearance.getCustomerPadTaxYqInterest();
        ar.setAmount(NumberUtils.add(NumberUtils.add(benjin, lixi), yanqilixi));
        ar.setCurrency(taxClearance.getCurrency());
        ar.setParentBillType("TaxClearance");
        ar.setParentBillCode(taxClearance.getTaxClearanceId());
        List < TarDetail > list = ListUtils.newArrayList();
        for (TaxClearanceDetail taxClearanceDetail : taxClearance.getTaxClearanceDetailList()) {
            if ("2".equals(taxClearanceDetail.getType())) {
                TarDetail detail = new TarDetail();
                detail.setCarId(taxClearance.getCarId());
                detail.setFrameNumber(taxClearance.getFrameNumber());
                detail.setExpenseItem("ITM00000007");
                detail.setApAmount(benjin);
                ServiceOrder serviceOrder = serviceOrderService.get(taxClearance.getServiceOrderId());
                for (ServiceOrderDetail serviceOrderDetail : serviceOrder.getServiceOrderDetailList()) {
                    if (serviceOrderDetail.getFrameNumber().equals(taxClearance.getFrameNumber())) {
                        detail.setBrand(serviceOrderDetail.getBrand());
                        detail.setArea(serviceOrderDetail.getArea());
                        detail.setModel(serviceOrderDetail.getModel());
                    }
                }
                list.add(detail);

                TarDetail detail1 = new TarDetail();
                detail1.setCarId(taxClearance.getCarId());
                detail1.setFrameNumber(taxClearance.getFrameNumber());
                detail1.setExpenseItem("ITM00000013");
                detail1.setApAmount(lixi);
                for (ServiceOrderDetail serviceOrderDetail : serviceOrder.getServiceOrderDetailList()) {
                    if (serviceOrderDetail.getFrameNumber().equals(taxClearance.getFrameNumber())) {
                        detail1.setBrand(serviceOrderDetail.getBrand());
                        detail1.setArea(serviceOrderDetail.getArea());
                        detail1.setModel(serviceOrderDetail.getModel());
                    }
                }
                list.add(detail1);

                TarDetail detail2 = new TarDetail();
                detail2.setCarId(taxClearance.getCarId());
                detail2.setFrameNumber(taxClearance.getFrameNumber());
                detail2.setExpenseItem("ITM00000039");
                detail2.setApAmount(yanqilixi);
                for (ServiceOrderDetail serviceOrderDetail : serviceOrder.getServiceOrderDetailList()) {
                    if (serviceOrderDetail.getFrameNumber().equals(taxClearance.getFrameNumber())) {
                        detail2.setBrand(serviceOrderDetail.getBrand());
                        detail2.setArea(serviceOrderDetail.getArea());
                        detail2.setModel(serviceOrderDetail.getModel());
                    }
                }
                list.add(detail2);
            }
        }
        ar.setTarDetailList(list);
        tarService.save(ar);
        t.setArId(ar.getArId());
        taxClearanceService.update(t);
        return renderResult(Global.TRUE, text("保存成功！"));
    }

    /**
     * 保存资方还税信息
     */
    @RequiresPermissions("financial:taxclearance:taxClearance:edit")
    @PostMapping(value = "investorTaxSave")
    @ResponseBody
    @Transactional(readOnly = false)
    public String investorTaxSave(TaxClearance t) {
        Date investorActualRepaymentDate = t.getInvestorActualRepaymentDate();
        TaxClearance taxClearance = taxClearanceService.get(t);
        double prepaidAmount = taxClearance.getPrepaidAmount();// 代垫金额
        InvestorFinancialInfo investorFinancialInfo = new InvestorFinancialInfo();
        investorFinancialInfo.setSupplier(taxClearance.getInvestor());
        investorFinancialInfo.setFinancingType("1");
        InvestorFinancialInfo info = investorFinancialInfoService.findList(investorFinancialInfo).get(0);
        Long investorYearDays = info.getDays();// 资方年天数
        List < TaxClearanceDetail > taxClearanceDetailList = taxClearance.getTaxClearanceDetailList();
        Double investorPadTaxInterest = 0D;
        ;        // 资方垫税利息
        Double investorPadTaxYqInterest = 0D;
        ;        // 资方垫税延期利息
        for (int i = 0; i < taxClearanceDetailList.size(); i++) {
            TaxClearanceDetail taxClearanceDetail = taxClearanceDetailList.get(i);
            if ("1".equals(taxClearanceDetail.getType())) {
                // 计算资方利息
                double investorDetailRatio = NumberUtils.div(Double.parseDouble(taxClearanceDetail.getInterestRate()), 100); //资方利率
                Double investorDetailDays = 0D;
                if (investorActualRepaymentDate.compareTo(taxClearanceDetail.getStartDate()) >= 0 && investorActualRepaymentDate.compareTo(taxClearanceDetail.getEndDate()) <= 0) {
                    investorDetailDays = DateUtils.getDistanceOfTwoDate(taxClearanceDetail.getStartDate(), investorActualRepaymentDate);
                } else if (investorActualRepaymentDate.compareTo(taxClearanceDetail.getStartDate()) >= 0 && investorActualRepaymentDate.compareTo(taxClearanceDetail.getEndDate()) > 0) {
                    investorDetailDays = DateUtils.getDistanceOfTwoDate(taxClearanceDetail.getStartDate(), taxClearanceDetail.getEndDate());
                }
                if (i == 0) {
                    investorPadTaxInterest = NumberUtils.mul(NumberUtils.div(NumberUtils.mul(prepaidAmount, investorDetailRatio), investorYearDays), investorDetailDays);
                } else {
                    double interest = NumberUtils.mul(NumberUtils.div(NumberUtils.mul(prepaidAmount, investorDetailRatio), investorYearDays), investorDetailDays);
                    investorPadTaxYqInterest = NumberUtils.add(investorPadTaxYqInterest, interest);
                }
            }
        }
        taxClearance.setInvestorActualDays((long) DateUtils.getDistanceOfTwoDate(taxClearance.getTaxPaymentDate(), investorActualRepaymentDate));
        taxClearance.setInvestorPadTaxInterest(investorPadTaxInterest);
        taxClearance.setInvestorPadTaxYqInterest(investorPadTaxYqInterest);
        taxClearanceService.save(taxClearance);
        // 生成资方应付
        Tap ap = new Tap();
        ap.setSupplierId(taxClearance.getInvestorId());
        ap.setDate(new Date());
        ap.setStatus1("1");
        ap.setBillStatus("2");// 已提交
        ap.setServiceOrderId(taxClearance.getServiceOrderId());
        double benjin = taxClearance.getPrepaidAmount();
        double lixi = taxClearance.getCustomerPadTaxInterest();
        double yanqilixi = taxClearance.getCustomerPadTaxYqInterest();
        ap.setAmount(NumberUtils.add(NumberUtils.add(benjin, lixi), yanqilixi));
        ap.setCurrency(taxClearance.getCurrency());
        ap.setParentBillType("TaxClearance");
        ap.setParentBillCode(taxClearance.getTaxClearanceId());
        List < TapDetail > list = ListUtils.newArrayList();
        for (TaxClearanceDetail taxClearanceDetail : taxClearance.getTaxClearanceDetailList()) {
            if ("1".equals(taxClearanceDetail.getType())) {
                TapDetail detail = new TapDetail();
                detail.setCarId(taxClearance.getCarId());
                detail.setFrameNumber(taxClearance.getFrameNumber());
                detail.setExpenseItem("ITM00000007");
                detail.setApAmount(benjin);
                ServiceOrder serviceOrder = serviceOrderService.get(taxClearance.getServiceOrderId());
                for (ServiceOrderDetail serviceOrderDetail : serviceOrder.getServiceOrderDetailList()) {
                    if (serviceOrderDetail.getFrameNumber().equals(taxClearance.getFrameNumber())) {
                        detail.setBrand(serviceOrderDetail.getBrand());
                        detail.setArea(serviceOrderDetail.getArea());
                        detail.setModel(serviceOrderDetail.getModel());
                    }
                }
                list.add(detail);

                TapDetail detail1 = new TapDetail();
                detail1.setCarId(taxClearance.getCarId());
                detail1.setFrameNumber(taxClearance.getFrameNumber());
                detail1.setExpenseItem("ITM00000013");
                detail1.setApAmount(lixi);
                for (ServiceOrderDetail serviceOrderDetail : serviceOrder.getServiceOrderDetailList()) {
                    if (serviceOrderDetail.getFrameNumber().equals(taxClearance.getFrameNumber())) {
                        detail1.setBrand(serviceOrderDetail.getBrand());
                        detail1.setArea(serviceOrderDetail.getArea());
                        detail1.setModel(serviceOrderDetail.getModel());
                    }
                }
                list.add(detail1);

                TapDetail detail2 = new TapDetail();
                detail2.setCarId(taxClearance.getCarId());
                detail2.setFrameNumber(taxClearance.getFrameNumber());
                detail2.setExpenseItem("ITM00000039");
                detail2.setApAmount(yanqilixi);
                for (ServiceOrderDetail serviceOrderDetail : serviceOrder.getServiceOrderDetailList()) {
                    if (serviceOrderDetail.getFrameNumber().equals(taxClearance.getFrameNumber())) {
                        detail2.setBrand(serviceOrderDetail.getBrand());
                        detail2.setArea(serviceOrderDetail.getArea());
                        detail2.setModel(serviceOrderDetail.getModel());
                    }
                }
                list.add(detail2);

            }

        }
        ap.setTapDetailList(list);
        tapService.save(ap);
        t.setApId(ap.getApId());
        taxClearanceService.update(t);
        return renderResult(Global.TRUE, text("保存成功！"));
    }

    /**
     * 代收代付
     *
     * @param taxClearance
     */
    @RequestMapping(value = "dsdf")
    @PostMapping(value = "dsdf")
    @ResponseBody
    @Transactional(readOnly = false)
    public String dsdf(TaxClearance taxClearance) {
        TaxClearance bill = taxClearanceService.get(taxClearance);
        // 应付
        if (StringUtils.isEmpty(bill.getApId())) {
            Tap ap = new Tap();
            ap.setSupplierId(bill.getInvestorId());
            ap.setDate(new Date());
            ap.setStatus1("1");
            ap.setBillStatus("2");// 已提交
            ap.setServiceOrderId(bill.getServiceOrderId());
            ap.setAmount(bill.getAmount());
            ap.setCurrency(bill.getCurrency());
            ap.setParentBillType("TaxClearance");
            ap.setParentBillCode(bill.getTaxClearanceId());
            List < TapDetail > list = ListUtils.newArrayList();
            TapDetail detail = new TapDetail();
            detail.setCarId(bill.getCarId());
            detail.setFrameNumber(bill.getFrameNumber());
            detail.setArea(bill.getArea());
            detail.setExpenseItem("ITM00000008");
            detail.setApAmount(bill.getAmount());
            ServiceOrder serviceOrder = serviceOrderService.get(bill.getServiceOrderId());
            for (ServiceOrderDetail serviceOrderDetail : serviceOrder.getServiceOrderDetailList()) {
                if (serviceOrderDetail.getFrameNumber().equals(bill.getFrameNumber())&&serviceOrderDetail.getRowNumber().equals(bill.getRowNumber())) {
                    detail.setRowNumber(bill.getRowNumber());
                    detail.setBrand(serviceOrderDetail.getBrand());
                    detail.setModel(serviceOrderDetail.getModel());
                }
            }
            list.add(detail);
            ap.setTapDetailList(list);
            tapService.save(ap);
            taxClearance.setApId(ap.getApId());
            taxClearanceService.update(taxClearance);
        }

        // 应收
        if (StringUtils.isEmpty(bill.getArId())) {
            Tar ar = new Tar();
            ar.setCustomer(bill.getCustomer());
            ar.setDate(new Date());
            ar.setStatus1("1");
            ar.setBillStatus("2");// 已提交
            ar.setServiceOrderId(bill.getServiceOrderId());
            ar.setAmount(bill.getAmount());
            ar.setCurrency(bill.getCurrency());
            ar.setParentBillType("TaxClearance");
            ar.setParentBillCode(bill.getTaxClearanceId());
            List < TarDetail > list = ListUtils.newArrayList();
            TarDetail detail = new TarDetail();
            detail.setCarId(bill.getCarId());
            detail.setFrameNumber(bill.getFrameNumber());
            detail.setArea(bill.getArea());
            detail.setExpenseItem("ITM00000008");
            detail.setApAmount(bill.getAmount());
            ServiceOrder serviceOrder = serviceOrderService.get(bill.getServiceOrderId());
            for (ServiceOrderDetail serviceOrderDetail : serviceOrder.getServiceOrderDetailList()) {
                if (serviceOrderDetail.getFrameNumber().equals(bill.getFrameNumber())&&serviceOrderDetail.getRowNumber().equals(bill.getRowNumber())) {
                    detail.setRowNumber(bill.getRowNumber());
                    detail.setBrand(serviceOrderDetail.getBrand());
                    detail.setModel(serviceOrderDetail.getModel());
                }
            }
            list.add(detail);
            ar.setTarDetailList(list);
            tarService.save(ar);
            taxClearance.setApId(ar.getArId());
            taxClearanceService.update(taxClearance);
        }
        return renderResult(Global.TRUE, text("生成成功！"));
    }

    /**
     * 垫税代理费
     *
     * @param taxClearance
     */

    @RequestMapping(value = "dlf")
    @PostMapping(value = "dlf")
    @ResponseBody
    @Transactional(readOnly = false)
    public String dlf(TaxClearance taxClearance) {
        TaxClearance bill = taxClearanceService.get(taxClearance);
        // 应收
        if (StringUtils.isEmpty(bill.getDlfArId())) {
            Tar ar = new Tar();
            ar.setCustomer(bill.getCustomer());
            ar.setDate(new Date());
            ar.setStatus1("1");
            ar.setBillStatus("2");// 已提交
            ar.setServiceOrderId(bill.getServiceOrderId());

            FixedExpense fixedExpense = new FixedExpense();
            fixedExpense.setFixedExpenseId("ITM00000005");
            FixedExpense fixedExpense1 = fixedExpenseService.get(fixedExpense);
            double price = fixedExpense1.getSalesPrice();
            for (CustomerPrice customerPrice : fixedExpense1.getCustomerPriceList()) {
                if (bill.getCustomer().getCustomerId().equals(customerPrice.getCustomerId())) {
                    price = customerPrice.getPrice();
                }
            }
            ar.setAmount(price);
            ar.setCurrency(bill.getCurrency());
            ar.setParentBillType("TaxClearance");
            ar.setParentBillCode(bill.getTaxClearanceId());
            List < TarDetail > list = ListUtils.newArrayList();
            TarDetail detail = new TarDetail();
            detail.setCarId(bill.getCarId());
            detail.setFrameNumber(bill.getFrameNumber());
            detail.setArea(bill.getArea());
            detail.setExpenseItem("ITM00000005");
            detail.setApAmount(price);
            ServiceOrder serviceOrder = serviceOrderService.get(bill.getServiceOrderId());
            for (ServiceOrderDetail serviceOrderDetail : serviceOrder.getServiceOrderDetailList()) {
                if (serviceOrderDetail.getFrameNumber().equals(bill.getFrameNumber())&&serviceOrderDetail.getRowNumber().equals(bill.getRowNumber())) {
                    detail.setRowNumber(bill.getRowNumber());
                    detail.setBrand(serviceOrderDetail.getBrand());
                    detail.setModel(serviceOrderDetail.getModel());
                }
            }
            list.add(detail);
            ar.setTarDetailList(list);
            tarService.save(ar);
            taxClearance.setDlfArId(ar.getArId());
            taxClearanceService.update(taxClearance);
        }
        return renderResult(Global.TRUE, text("生成成功！"));
    }

    /**
     * 保证金预付
     *
     * @param taxClearanceDetail
     */

    @RequestMapping(value = "bzjyf")
    @PostMapping(value = "bzjyf")
    @ResponseBody
    @Transactional(readOnly = false)
    public String bzjyf(TaxClearanceDetail taxClearanceDetail) {
        TaxClearanceDetail detail = taxClearanceDetailDao.get(taxClearanceDetail);
        TaxClearance taxClearance = taxClearanceService.get(detail.getTaxClearanceId());
        if (StringUtils.isEmpty(detail.getPrepaymentId())) {
            //生成预付
            Tprepayment tprepayment = new Tprepayment();
            tprepayment.setSupplierId(taxClearance.getInvestorId());
            tprepayment.setDate(new Date());
            tprepayment.setStatus1("1");
            tprepayment.setServiceOrderId(taxClearance.getServiceOrderId());
            tprepayment.setCurrency(taxClearance.getCurrency());
            tprepayment.setBillStatus("2");// 已提交
            tprepayment.setParentBillType("TaxClearance");
            tprepayment.setParentBillCode(taxClearance.getTaxClearanceId());
            tprepayment.setEstimatedPaymentAmount(detail.getMarginAmount());
            TprepaymentEstimated tprepaymentEstimated = new TprepaymentEstimated();
            tprepaymentEstimated.setFrameNumber(taxClearance.getFrameNumber());
            tprepaymentEstimated.setRowNumber(taxClearance.getRowNumber());
            tprepaymentEstimated.setPrepaymentType("ITM00000002");
            tprepaymentEstimated.setEstimatedPaymentAmount(detail.getMarginAmount());
            tprepaymentEstimated.setPaymentAmountActual(0D);
            tprepaymentEstimated.setPaymentAmountEstimated(detail.getMarginAmount());
            tprepayment.getTprepaymentEstimatedList().add(tprepaymentEstimated);
            tprepaymentService.save(tprepayment);

            TaxClearanceDetail d = new TaxClearanceDetail();
            d.setTaxClearanceDetailId(detail.getTaxClearanceDetailId());
            d.setPrepaymentId(tprepayment.getPrepaymentId());
            taxClearanceDetailDao.update(d);
        }
        return renderResult(Global.TRUE, text("生成成功！"));
    }

    /**
     * 保证金预收
     *
     * @param taxClearanceDetail
     */

    @RequestMapping(value = "bzjys")
    @PostMapping(value = "bzjys")
    @ResponseBody
    @Transactional(readOnly = false)
    public String bzjys(TaxClearanceDetail taxClearanceDetail) {
        TaxClearanceDetail detail = taxClearanceDetailDao.get(taxClearanceDetail);
        TaxClearance taxClearance = taxClearanceService.get(detail.getTaxClearanceId());
        if (StringUtils.isEmpty(detail.getPrepaymentId())) {
            //生成预收
            TadvancesReceived tadvancesReceived = new TadvancesReceived();
            tadvancesReceived.setCustomerId(taxClearance.getCustomer().getCustomerId());
            tadvancesReceived.setDate(new Date());
            tadvancesReceived.setStatus1("1");
            tadvancesReceived.setServiceOrderId(taxClearance.getServiceOrderId());
            tadvancesReceived.setCurrency(taxClearance.getCurrency());
            tadvancesReceived.setBillStatus("2");// 已提交
            tadvancesReceived.setParentBillType("TaxClearance");
            tadvancesReceived.setParentBillCode(taxClearance.getTaxClearanceId());
            tadvancesReceived.setRowNumber(taxClearance.getRowNumber());
            tadvancesReceived.setEstimatedReceivedAmount(detail.getMarginAmount());
            TadvancesReceivedEstimated tadvancesReceivedEstimated = new TadvancesReceivedEstimated();
            tadvancesReceivedEstimated.setFrameNumber(taxClearance.getFrameNumber());
            tadvancesReceivedEstimated.setAdvancesReceivedType("ITM00000002");
            tadvancesReceivedEstimated.setEstimatedReceivedAmount(detail.getMarginAmount());
            tadvancesReceivedEstimated.setReceivedAmountActual(0D);
            tadvancesReceivedEstimated.setReceivedAmountEstimated(detail.getMarginAmount());
            tadvancesReceived.getTadvancesReceivedEstimatedList().add(tadvancesReceivedEstimated);
            tadvancesReceivedService.save(tadvancesReceived);

            TaxClearanceDetail d = new TaxClearanceDetail();
            d.setTaxClearanceDetailId(detail.getTaxClearanceDetailId());
            d.setAdvancesReceivedId(tadvancesReceived.getAdvancesReceivedId());
            taxClearanceDetailDao.update(d);
        }
        return renderResult(Global.TRUE, text("生成成功！"));
    }
}
